package com.ssy.lingxi.member.merchant.model.convert;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.member.merchant.model.vo.basic.request.FileUploadVO;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.ArrayList;
import java.util.List;

/**
*  附件改成json
* @author wrc
* @date 2020/11/12
*/
@Converter(autoApply = true)
public class JpaJsonToFileUploadVOConverter implements AttributeConverter<List<FileUploadVO>, String> {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(List<FileUploadVO> attribute) {
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR, "数据库Json字段写入错误");
        }
    }

    @Override
    public List<FileUploadVO> convertToEntityAttribute(String dbData) {
        try {
            if (dbData == null) {
                return new ArrayList<>();
            }
            return objectMapper.readValue(dbData, new TypeReference<List<FileUploadVO>>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR, "数据库Json字段写入错误");
        }
    }
}
